import { Socket } from "./Socket";
import { PacketBuffer } from "./PacketBuffer";

export class ClientSocket extends Socket
{
    public static ClassName:string = "ClientSocket";
    private buffer:PacketBuffer;
    private serverHost:string;
    public constructor()
    {
        super();
        this.buffer = new PacketBuffer();
    }
    public connectByUrl(url:string):void 
    {
        console.log(">>>>>>",url);
        
        this.serverHost = url;
        this.reconnect();
    }
    public reconnect():void
    {
        if(this.connected)this.close();
        if(this.serverHost==null||this.serverHost=="")return;
        setTimeout(() => super.connectByUrl(this.serverHost), 1);
    }
    protected onSocketGetData(data:any):void
    {
        if(data)
        {
            // this.buffer.push(new Uint8Array(data));
            // data = this.buffer.packetBytes;
            this.buffer.push(data);
            super.onSocketGetData(data);
        }
    }
    public send(byte:any):void
    {
        if(byte==null)return;
        super.send(byte);
    }

    public sendString(str:string):void
    {
        if(str==null||str=="")return;
        super.send(str);
    }
    public close():void
    {
        super.close();
        this.buffer.clear();
    }
    public dispose():void
    {
        super.dispose();
        this.buffer = null;
    }
    public get socketBytes():Array<string>{return this.buffer.packetBytes;}
}